package com.sxyc.weixin.controller;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.TemplateData;
import com.jfinal.weixin.sdk.api.TemplateMsgApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.sxyc.tintin.model.BreakRoules;
import com.sxyc.tintin.model.CarInfo;
import com.sxyc.tintin.model.Device;
import com.sxyc.tintin.model.DeviceBinding;
import com.sxyc.tintin.model.Person;
import com.sxyc.utils.WeixinUtil;

public class TemplateController extends ApiController {

	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的 ApiConfig 对象即可 可以通过在请求 url 中挂参数来动态从数据库中获取
	 * ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		return WeixinUtil.getApiConfig();
	}
	
	  /**
     * 查询违章
     */
    public void juheQuery(){
    	//违章illegoCode
    	String illegoCode="";
    	//违章原因
    	String illegoreason="";
    	String code = getPara("code");
		String openId = (String) getRequest().getSession().getAttribute("openId");
		if(openId == null && code == null){
			String url = SnsAccessTokenApi.getAuthorizeURL(PropKit.get("appId"),PropKit.get("domain")+"/template/juheQuery", true);
			redirect(url);
		}else{
			if(openId == null){
				SnsAccessToken accessToken = SnsAccessTokenApi.getSnsAccessToken(getApiConfig().getAppId(), getApiConfig().getAppSecret(),code);
				if(accessToken == null){
					return;
				}
				openId = accessToken.getOpenid();
				getRequest().getSession().setAttribute("openId", openId);
			}
			Record person = Db.findFirst("select ptel,pcity,pcarNum,pengineNum,pframeNum from person where openid = ?",openId);
			if(person == null){
				render("register.jsp");
				return;
			}else if(person.get("ptel") == null){
				render("register.jsp");
				return;	
			}else if(person.get("pcarNum") == null){
				render("carInfo.jsp");
				return;
			}else{
				String hphm = person.getStr("pcarNum");
				int count = 0;
				int fens = 0;
				int moneys = 0;
				//获取城市查询接口参数要求（车架号、发动机号）
				String city = person.get("pcity").toString();
				if(city.endsWith("市")){
					city = city.substring(0, city.length()-1);
				}
				Record juheCity = Db.findFirst("select City_code,`Engine`,Engineno,Classa,Classno from juhe where city = ?",city);
				if(juheCity ==null){
					//车辆所在城市暂不支持查询
					illegoCode="2";
					illegoreason="您好,您的车辆所在城市暂不支持查询";
				}else{
					//处理车架号和发动机号
					String engineno = "";
					String classno = "";
					if(juheCity.getInt("Engine") == 1){//1,需要发动机号  0,不需要发动机号
						if(juheCity.getInt("Engineno") == 0){//0,需要全部发动机号  1-9,需要后几位
							engineno = person.get("pengineNum");
						}else{
							String engine = person.get("pengineNum").toString();
							engineno = engine.substring(engine.length()-juheCity.getInt("Engineno")-1);
						}
					}
					if(juheCity.getInt("Classa") == 1){//1,需要车架号  0,不需要车架号
						if(juheCity.getInt("Classno") == 0){//0,需要全部车架号  1-9,需要后几位
							classno = person.get("pframeNum");
						}else{
							String classa = person.get("pframeNum").toString();
							classno = classa.substring(classa.length()-juheCity.getInt("Classno"));
						}
					}
					
					System.out.println("违章查询开始……");
					JuheController juhe = new JuheController();
					//聚合违章查询
					JSONObject res = juhe.getRequest2(juheCity.getStr("City_code"), person.getStr("pcarNum"), engineno, classno);
					LogKit.warn("违章查询结果 ："+res);
					System.out.println(res == null);
					if(res != null){
						if(res.getInteger("error_code")!=0){
							//如果返回结果的error_code错误
				            System.out.println(res.get("error_code")+":"+res.get("reason"));
							illegoCode=res.get("error_code").toString();
							illegoreason=res.get("reason").toString();
						}else{
					        JSONObject result = res.getJSONObject("result");
							JSONArray lists = result.getJSONArray("lists");
							List<BreakRoules> breakRoules = new ArrayList<>();
							BreakRoules roules = new BreakRoules();
							for (Object object : lists) {
								JSONObject list = JSONObject.parseObject(object.toString());
								//System.out.println(list);
								roules = new BreakRoules(list.getString("date"), list.getString("area"), list.getString("act"), list.getString("fen"), list.getString("money"), list.getString("handled"));
								breakRoules.add(roules);
								if(list.getInteger("handled") == 0){
									count++;fens++;
									moneys += list.getInteger("money");
								}
							}
							//暂无违规记录
							if(breakRoules.size()==0){
								illegoCode="3";
								illegoreason="哇哦！没有违章，你好棒！";
							}else{
								illegoCode="0";
							}
							setAttr("lists", breakRoules);
						}
					}else{//如果返回结果为空
			            LogKit.warn("查询结果为空！");
						illegoCode= "-1";
						illegoreason="查询失败！请重试！";
			        }
					setAttr("hphm", hphm);
					setAttr("count", count);
					setAttr("fens", fens);
					setAttr("moneys", moneys);
				}
			}
			setAttr("illegoCode", illegoCode);
			setAttr("illegoreason", illegoreason);
			//修改第三期
			render("weizhang-message.jsp");
		}
    }
    
    /**
     * 违章告警通知
     * @param openId
     * @param hphm	车牌号
     * @param date	违章时间
     * @param area	地点
     * @param act	原因
     * @param fen	扣分
     * @param money	罚款
     */
    public void templateJuhe(String openId, String hphm, String date, String area, String act, String fen, String money) {
    	String template = "cd6TU9zELUfnfCg8mPId2aDTaRZfTUKW7jwrJ_EHvc4";
    	String url = PropKit.get("domain")+"template/juheQuery";
    	ApiResult result = TemplateMsgApi.send(TemplateData.New()
                // 消息接收者
                .setTouser(openId)
                // 模板id
                .setTemplate_id(template)
                .setTopcolor("#eb414a")
                .setUrl(url)

                // 模板参数
                .add("first", "您好，主人。您有一次违章还未处理：", "#222222")
                .add("keyword1", hphm, "#777777")
                .add("keyword2", date, "#777777")
                .add("keyword3", area, "#777777")
                .add("keyword4", act, "#777777")
                .add("remark", "易行丁丁提醒您：安全驾驶,一路平安。", "#C90B14")
                .build());
    	
    	renderText(result.getJson());
	}
		
	public void editCarInfo(){
		
	}
	
	//支付通知接口
    public void templatePay(){
    	String openId = getPara("openid");
       	String tel = getPara("tel");
      	String money = getPara("money");
      	paynotify(openId, tel, money);
    }
    
    //支付通知模板消息
    public void paynotify(String openId, String iccid, String money) {
    	String template = "kwcc250bUIYchRav0VQ972n_ZBTS_2oxb3owQlX_bfc";
    	String url = "";
    	ApiResult result = TemplateMsgApi.send(TemplateData.New()
                // 消息接收者
                .setTouser(openId)
                // 模板id
                .setTemplate_id(template)
                .setTopcolor("#eb414a")
                .setUrl(url)

                // 模板参数
                .add("first", "您好，主人。您已成功充值。", "#222222")
                .add("accountType", "iccid号", "#000000")
                .add("account", iccid, "#777777")
                .add("amount", "￥"+money+"元", "#777777")
                .add("result", "充值成功", "#777777")
                .add("remark", "叮当物流提醒您：您已充值成功，我们会尽快为您处理。如有疑问，请致电<a>029-88447656</a>联系我们。感谢您的使用！", "#777777")
                .build());
    	
    	renderText(result.getJson());
	}
    
    //油卡支付通知模板消息
    public void paynotify2(String openId, String cardnum, String money) {
    	String template = "kwcc250bUIYchRav0VQ972n_ZBTS_2oxb3owQlX_bfc";
    	String url = "";
    	ApiResult result = TemplateMsgApi.send(TemplateData.New()
                .setTouser(openId)
                .setTemplate_id(template)
                .setTopcolor("#eb414a")
                .setUrl(url)
                .add("first", "您好，主人。您已成功充值。", "#222222")
                .add("accountType", "加油卡号", "#000000")
                .add("account", cardnum, "#777777")
                .add("amount", "￥"+money+"元", "#777777")
                .add("result", "充值成功", "#777777")
                .add("remark", "叮当物流提醒您：您已充值成功，我们会尽快为您处理。如有疑问，请致电<a>029-88447656</a>联系我们。感谢您的使用！", "#777777")
                .build());
    	
    	renderText(result.getJson());
	}
    
}

